package com.jackstraw.jack_base.datasource.database.parten.entity.bean;

import com.jackstraw.jack_base.datasource.common.entity.AbstractTemplate;
import com.jackstraw.jack_base.datasource.common.entity.DataSourceRouting;
import com.jackstraw.jack_base.datasource.database.parten.entity.DataBaseEntity;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class DataBaseRouting<DBE extends DataBaseEntity<DBE>, DBP extends DataBaseProperties<DBE>>
        extends DataSourceRouting<DataBasePropertiesEntity<DBE>, DataBaseTemplate<DBE>, DataBaseProperties<DBE>, DataBaseRouting<DBE, DBP>>
        implements DataSource {

    private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();


    @Override
    public Connection getConnection() throws SQLException {
        return determineTargetEntity().get().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return determineTargetEntity().get().getConnection(username, password);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException("getLogWriter");
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException("setLogWriter");
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException("setLoginTimeout");
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        if (iface.isInstance(this)) {
            return (T) this;
        }
        return determineTargetEntity().get().unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return (iface.isInstance(this) || determineTargetEntity().get().isWrapperFor(iface));
    }

    @Override
    public Object resolveSpecifiedEntity(Object entity) {
        if (entity instanceof String) {
            return this.dataSourceLookup.getDataSource((String) entity);
        } else if (entity instanceof AbstractTemplate) {
            return entity;
        } else {
            throw new IllegalArgumentException(
                    "Illegal data source value - only [javax.sql.DataSource] and String supported: " + entity);
        }
    }

}
